package server_commands;

import java.sql.SQLException;
import java.util.StringTokenizer;

import static server.RLM_Server.activeConnections;

import server.ServerSocketConnection;
import connection_modul.DatabaseConnection;

public class UNBLOCKCommand extends Command {

	public UNBLOCKCommand(String parameter) {	
		
		setCode(UNBLOCK_CMD);
		setParameter(parameter);
	}
	
	@Override
	/**
	 * Metoda izvrsava UNBLOCK komandu tj brise korisnika kojeg treba deblokirati
	 * iz odgovarajuce tabele u bazi podataka. Klijentu se salje odgovor o
	 * uspesnosti akcije. Blokirani korisnik se obavestava o novom statusu, nickname-u i
	 * avataru.
	 * 
	 * @param connection - konekcija ka klijentu
	 * @param dbConnection - objekat za rad sa bazom
	 */
	public boolean executeCommand(ServerSocketConnection connection, DatabaseConnection dbConnection) {
		
		StringTokenizer tokenizer = new StringTokenizer(getParameter());
		
		String username = tokenizer.nextToken();
		String contactToUnblock = tokenizer.nextToken();
		String nickname = tokenizer.nextToken();	
		String email = tokenizer.nextToken();
		String status = tokenizer.nextToken();
		String avatar = tokenizer.nextToken();
		
		try {
			dbConnection.doUpdateStatement("DELETE FROM tblBlocks " +
							"WHERE tblBlocks.user_source = '" + username + "' AND " +
							"tblBlocks.user_dest = '" + contactToUnblock + "'");		
		
			ServerSocketConnection tempConnection = activeConnections.get(contactToUnblock);		
		
			if (tempConnection != null) {
				tempConnection.setMessage("SERV_CHSTATUS " + username + " " + status + " " + nickname + " " + email + " " + avatar);
//				tempConnection.setMessage("SERV_UNBLOCK " + username);
			}
		
			connection.setMessage("100 User unblocked.");
		}		
		catch (SQLException e) {	
			dbConnection.doRollBack();
			e.printStackTrace();
			return false;
		}
		
		dbConnection.doCommit();
		
		return true;
	}

}
